package com.my.financial.repository;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.my.financial.controller.form.PageInfo;
import com.my.financial.controller.form.QueryForm;
import com.my.financial.domain.FinancialItem;

@Repository
public class FinancialItemRepository {
	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getSession() {
		return this.sessionFactory.getCurrentSession();
	}
	
	public void save(FinancialItem item){
		getSession().save(item);
	}
	
	public void delete(FinancialItem financialItem) {
		getSession().delete(financialItem);
	}
	
	public void batchDelete(String multiId) {
		for(String str:multiId.split(",")){
			getSession().delete(new FinancialItem(Long.parseLong(str)));
		}
	}
	
	public void update(FinancialItem financialItem) {
		getSession().update(financialItem);
	}
	
	@SuppressWarnings("unchecked")
	public List<FinancialItem> findByQueryForm(QueryForm queryForm, PageInfo pi) {
		final int CountPerPage = pi.getCountPerPage();
		/*从第几行开始*/
		final int rowNum = CountPerPage * (pi.getPageNum() - 1);

		String listHql = this.getHql(queryForm);

		Query listQuery = this.getSession().createQuery(listHql.toString());
		setQueryHql(queryForm, listQuery, listHql);
		listQuery.setFirstResult(rowNum);
		listQuery.setMaxResults(CountPerPage);

		return listQuery.list();
	}

	public PageInfo findPageInfo(QueryForm queryForm, PageInfo pi) {
		String countHql = "select count( fi.id) " + this.getHql(queryForm);

		Query countQuery = this.getSession().createQuery(countHql.toString());
		setQueryHql(queryForm, countQuery, countHql);

		Long count = (Long) countQuery.uniqueResult();
		pi.setTotalRows(count.intValue());
		return pi;
	}

	private void setQueryHql(QueryForm queryForm, Query query, String hql) {
		query.setParameter("userId",queryForm.getUser().getId());
		if (hql.contains("type")) {
			query.setParameter("type", queryForm.getType());
		}
		if (hql.contains("item")) {
			query.setParameter("item", queryForm.getItem());
		}
		if(hql.contains("member")){
			query.setParameter("member",queryForm.getMember());
		}
		if (hql.contains("startTime")) {
			try {
				DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd"); 
				query.setParameter("startTime",fmt.parse(queryForm.getStarttime()) );
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (hql.contains("endTime")) {
			try {
				DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd"); 
				query.setParameter("endTime",fmt.parse(queryForm.getEndtime()) );
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
	}

	private String getHql(QueryForm queryForm) {
		final String type = queryForm.getType();
		final String item = queryForm.getItem();
		final String startTime = queryForm.getStarttime();
		final String endTime = queryForm.getEndtime();
		final String member = queryForm.getMember();

		String mainStr = " from " + FinancialItem.class.getName() + " fi where user_id=:userId ";
		StringBuffer hql = new StringBuffer();
		hql.append(mainStr);

		if (StringUtils.isNoneBlank(type)&&!type.equals("全部")) {
			hql.append(" and fi.type=:type ");
		} 
		if (StringUtils.isNoneBlank(item)&&!item.equals("全部")) {
			hql.append(" and fi.item=:item ");
		}
		if (StringUtils.isNoneBlank(member)&&!member.equals("全部")) {
			hql.append(" and fi.member=:member ");
		} 
		if (StringUtils.isNoneBlank(startTime)) {
			hql.append(" and fi.createTime>=:startTime ");
		}
		if (StringUtils.isNoneBlank(endTime)) {
			hql.append(" and fi.createTime<=:endTime ");
		} 
		return hql.toString();
	}
}
